package controller

import (
	"blog/database"
	"blog/middleware"
	"blog/model/article"
	"blog/model/base"
	"blog/router"
	"blog/types"
	"blog/utils"
	"fmt"
	"github.com/gin-gonic/gin"
)

var cateCtrl *_CategoryControl

type _CategoryControl struct {
	types.Codes
	article.AkArticleCategory
	base.BaseModel
}

func init() {

	cateCtrl = &_CategoryControl{}

	router.Router.POST("/article/category/add", middleware.JWT(), cateCtrl.add)

	router.Router.GET("/article/category/list", middleware.JWT(), cateCtrl.list)

	router.Router.PUT("/article/category/edit", middleware.JWT(), cateCtrl.edit)

}

func (cateCtrl *_CategoryControl) edit(c *gin.Context) {

	var editDto []struct {
		Id         int64 `json:"id"`
		Deleted    int8  `json:"deleted"`
		ActiveFlag int8  `json:"activeFlag"`
	}

	err := c.ShouldBindJSON(&editDto)
	if err != nil {

		utils.Error(c, 400, err.Error())

		return
	}

	for i := 0; i < len(editDto); i++ {

		article := article.AkArticleCategory{}

		database.GetDB().First(&article, editDto[i].Id)

		if article.ID <= 0 {

			continue

		}

		database.GetDB().Model(&article).Updates(map[string]interface{}{"deleted": editDto[i].Deleted, "active_flag": editDto[i].ActiveFlag})

	}

	utils.Success(c, nil)

}

func (cateCtrl *_CategoryControl) list(c *gin.Context) {

	pageGination := struct {
		types.Pagination
		Name string `json:"name" form:"name" uri:"name"`
		Pid  int64  `json:"pid" form:"pid" uri:"pid"`
	}{}

	err := c.ShouldBindQuery(&pageGination)

	if err != nil {

		utils.Error(c, 400, err.Error())
		return

	}

	var categoryList []article.AkArticleCategory

	var count int64
	query := map[string]interface{}{}
	query["deleted"] = 0

	if pageGination.Pid >= 0 {

		query["pid"] = pageGination.Pid

	}

	if len(pageGination.Name) == 0 {

		database.GetDB().Table(cateCtrl.TableName()).Where(query).Offset(pageGination.Limit * pageGination.Page).Limit(pageGination.Limit).Find(&categoryList).Count(&count)

	} else {

		database.GetDB().Table(cateCtrl.TableName()).Where(query).Where(fmt.Sprintf(" name like '%%%s%%' ", pageGination.Name)).Offset(pageGination.Limit * pageGination.Page).Limit(pageGination.Limit).Find(&categoryList).Count(&count)

	}

	list := []article.AkArticleCategory{}

	for _, item := range categoryList {

		itm := &article.AkArticleCategory{}

		id := item.ID

		database.GetDB().Model(&article.AkArticleCategory{}).Where("pid = ?", id).First(&itm)

		if itm.ID > 0 {

			item.HasChildren = true

		} else {

			item.HasChildren = false

		}

		list = append(list, item)

	}

	utils.SuccessList(c, list, count)

}

func (cateCtrl *_CategoryControl) add(c *gin.Context) {

	cat := struct {
		Name string `json:"name" binding:"required"`
		Pid  int64  `json:"pid" binding:"required"`
	}{}

	c.ShouldBindJSON(&cat)

	var time, _ = types.ParseNow()

	category := article.AkArticleCategory{
		BaseModel: base.BaseModel{
			CreateTime: time,
		},
		Name: cat.Name,
		Pid:  cat.Pid,
	}

	result := database.GetDB().Table(cateCtrl.TableName()).Create(&category)

	if result.Error != nil {

		var code = cateCtrl.SUCCESS

		c.JSON(code, cateCtrl.GetMessage(code))

	} else {

		var code = cateCtrl.FAILED

		c.JSON(400, cateCtrl.GetMessage(code))

	}

}
